<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="营业模式" prop="storeId">
        <el-select v-model="queryParams.storeId" placeholder="请选择营业模式" clearable>
          <el-option v-for="(label, value) in businessPatternMap" :key="value" :label="label" :value="parseInt(value)" />
        </el-select>
      </el-form-item>
      <el-form-item label="星期几" prop="dayOfWeek">
        <el-select v-model="queryParams.dayOfWeek" placeholder="请选择星期几" clearable>
          <el-option v-for="(label, value) in dayOfWeekMap" :key="value" :label="label" :value="parseInt(value)" />
        </el-select>
      </el-form-item>
      <el-form-item label="营业开始时间" prop="openTime">
        <el-time-picker
          v-model="queryParams.openTime"
          placeholder="请选择营业开始时间"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          clearable>
        </el-time-picker>
      </el-form-item>
      <el-form-item label="营业结束时间" prop="closeTime">
        <el-time-picker
          v-model="queryParams.closeTime"
          placeholder="请选择营业结束时间"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          clearable>
        </el-time-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['core:storeBusinessTime:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['core:storeBusinessTime:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['core:storeBusinessTime:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['core:storeBusinessTime:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeBusinessTimeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="营业模式" align="center" prop="storeId">
        <template #default="scope">
          {{ businessPatternMap[scope.row.storeId] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="星期几" align="center" prop="dayOfWeek">
        <template #default="scope">
          {{ dayOfWeekMap[scope.row.dayOfWeek] || '未知' }}
        </template>
      </el-table-column>
      <el-table-column label="营业开始时间" align="center" prop="openTime" width="120">
        <template #default="scope">
          <span>{{ formatTime(scope.row.openTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="营业结束时间" align="center" prop="closeTime" width="120">
        <template #default="scope">
          <span>{{ formatTime(scope.row.closeTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['core:storeBusinessTime:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['core:storeBusinessTime:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改门店营业时间配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="storeBusinessTimeRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="营业模式" prop="storeId">
          <el-select 
            v-model="form.storeId" 
            placeholder="请选择营业模式" 
            style="width: 100%"
            :disabled="form.id != null"
          >
            <el-option v-for="(label, value) in businessPatternMap" :key="value" :label="label" :value="parseInt(value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="星期几" prop="dayOfWeek">
          <el-select v-model="form.dayOfWeek" placeholder="请选择星期几" style="width: 100%">
            <el-option v-for="(label, value) in dayOfWeekMap" :key="value" :label="label" :value="parseInt(value)" />
          </el-select>
        </el-form-item>
        <el-form-item label="营业开始时间" prop="openTime">
          <el-time-picker
            v-model="form.openTime"
            placeholder="请选择营业开始时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            style="width: 100%"
            clearable>
          </el-time-picker>
        </el-form-item>
        <el-form-item label="营业结束时间" prop="closeTime">
          <el-time-picker
            v-model="form.closeTime"
            placeholder="请选择营业结束时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            style="width: 100%"
            clearable>
          </el-time-picker>
        </el-form-item>
        <el-form-item label="逻辑删除标志" prop="delFlag" v-if="false">
          <el-input v-model="form.delFlag" placeholder="请输入逻辑删除标志" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="StoreBusinessTime">
import { listStoreBusinessTime, getStoreBusinessTime, delStoreBusinessTime, addStoreBusinessTime, updateStoreBusinessTime } from "@/api/core/storeBusinessTime"
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()

// 数据映射字典
const businessPatternMap = { 
  1: '统一时间模式', 
  2: '周末延长模式', 
  3: '周末高峰模式', 
  4: '24小时营业模式' 
}

const dayOfWeekMap = {
  1: '星期一',
  2: '星期二', 
  3: '星期三',
  4: '星期四',
  5: '星期五',
  6: '星期六',
  7: '星期日'
}

const storeBusinessTimeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 格式化时间显示（从ISO时间字符串中提取时分秒）
function formatTime(timeString) {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    const seconds = date.getSeconds().toString().padStart(2, '0')
    return `${hours}:${minutes}:${seconds}`
  } catch (error) {
    return timeString
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    storeId: null,
    dayOfWeek: null,
    openTime: null,
    closeTime: null,
  },
  rules: {
    storeId: [
      { required: true, message: "请选择营业模式", trigger: "change" }
    ],
    dayOfWeek: [
      { required: true, message: "请选择星期几", trigger: "change" }
    ],
    openTime: [
      { required: true, message: "营业开始时间不能为空", trigger: "blur" }
    ],
    closeTime: [
      { required: true, message: "营业结束时间不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询门店营业时间配置列表 */
function getList() {
  loading.value = true
  listStoreBusinessTime(queryParams.value).then(response => {
    storeBusinessTimeList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    storeId: 1,
    dayOfWeek: 1,
    openTime: null,
    closeTime: null,
    delFlag: 0,
    createTime: null
  }
  proxy.resetForm("storeBusinessTimeRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加门店营业时间配置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getStoreBusinessTime(_id).then(response => {
    form.value = response.data
    // 将时间格式化为 HH:mm:ss 格式用于时间选择器
    if (form.value.openTime) {
      form.value.openTime = formatTime(form.value.openTime)
    }
    if (form.value.closeTime) {
      form.value.closeTime = formatTime(form.value.closeTime)
    }
    open.value = true
    title.value = "修改门店营业时间配置"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["storeBusinessTimeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStoreBusinessTime(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addStoreBusinessTime(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除门店营业时间配置编号为"' + _ids + '"的数据项？').then(function() {
    return delStoreBusinessTime(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('core/storeBusinessTime/export', {
    ...queryParams.value
  }, `storeBusinessTime_${new Date().getTime()}.xlsx`)
}

getList()
</script>
